<template>
  <div id="order-list">
    <div class="search-box">
      <Row type="flex">
        <Row type="flex"
             justify="start"
             class="search-item-left">
          <Col class="search-item">
          <span class="search-label">支付流水号:</span>
          <Input v-model="searchObj.transactionId"
                 placeholder="请输入"
                 :maxlength="100">
          </Input>
          </Col>
          <Col class="search-item">
          <span class="search-label">订单编号:</span>
          <Input v-model="searchObj.orderCode"
                 placeholder="请输入">
          </Input>
          </Col>
          <Col class="search-item">
          <span class="search-label">订单类型:</span>
          <Select v-model="searchObj.orderType"
                  @on-change="doSearch">
            <Option v-for="item in orderTypeList"
                    :value="item.value"
                    :key="item.value">{{ item.label }}</Option>
          </Select>
          </Col>
          <Col class="search-item">
          <Button class="search-btn"
                  type="primary"
                  @click="doSearch(2)">查询</Button>
          </Col>
          <Col class="search-item">
          <Button class="search-btn"
                  @click="resetBtn">重置</Button>
          </Col>
        </Row>
        <Row type="flex"
             justify="end"
             class="search-item-right">
          <Col class="search-item">
          <Button v-if="exampleShow"
                  @click="exampleOpen">收起筛选
            <Icon type="ios-arrow-down" />
          </Button>
          <Button v-else
                  @click="exampleOpen">更多筛选
            <Icon type="ios-arrow-up" />
          </Button>
          </Col>
        </Row>
      </Row>
      <div class="search-example"
           v-show="exampleShow">
        <Row type="flex">
          <Col class="search-item">
          <span class="search-label">订单状态:</span>
          <Select v-model="searchObj.orderStatus"
                  @on-change="doSearch">
            <Option v-for="item in orderStatus"
                    :value="item.value"
                    :key="item.value">{{ item.label }}</Option>
          </Select>
          </Col>
          <Col class="search-item">
          <span class="search-label">门店名称:</span>
          <Select v-model="searchObj.shopId"
                  :max-tag-count="1"
                  :max-tag-placeholder="maxTagPlaceholder"
                  filterable
                  multiple
                  class="select-shop-item"
                  @on-change="doSearch">
            <Option v-for="item in shopList"
                    :value="item.shopId"
                    :key="item.shopId">{{ item.shopName }}</Option>
          </Select>
          </Col>
          <!-- <Col class="search-item">
          <span class="search-label">支付类型:</span>
          <Select v-model="searchObj.payType" @on-change="doSearch">
            <Option v-for="item in payType" :value="item.value" :key="item.value">{{ item.label }}</Option>
          </Select>
          </Col> -->
          <!-- <Col class="search-item">
          <span class="search-label">物流状态:</span>
          <Select v-model="searchObj.logisticsStatus"
                  @on-change="doSearch">
            <Option v-for="item in logisticsStatus"
                    :value="item.value"
                    :key="item.value">{{ item.label }}</Option>
          </Select>
          </Col> -->
          <!-- <Col class="search-item">
          <span class="search-label">门店ID:</span>
          <Input v-model="searchObj.shopId"
                 placeholder="请输入"> -->
          <!-- <Icon type="ios-search" slot="suffix"  @click="doSearch"/> -->
          <!-- </Input> -->
          <!-- </Col> -->
          <Col class="search-item">
          <span class="search-label">顾客姓名:</span>
          <Input v-model="searchObj.customerName"
                 @on-keyup='filterSpace'
                 placeholder="请输入">
          <!-- <Icon type="ios-search" slot="suffix"  @click="doSearch"/> -->
          </Input>
          </Col>
          <Col class="search-item">
          <span class="search-label">支付方式:</span>
          <Select v-model="searchObj.payMethod"
                  @on-change="doSearch">
            <Option v-for="item in payMethod"
                    :value="item.value"
                    :key="item.value">{{ item.label }}</Option>
          </Select>
          </Col>
          <Col class="search-item">
          <span class="search-label">创建时间:</span>
          <Poptip trigger="hover"
                  content="查询间隔时间最大为7天"
                  placement="bottom-end">
            <!-- <DatePicker ref="creationTime" :editable="false" @on-change="selectTime" v-model="dateTimes" format="yyyy-MM-dd HH:mm:ss" placement="bottom" type="daterange" :options='dateRangeDisabledOptions' @on-clear='clearDatePicker'> -->
            <DatePicker ref="creationTime"
                        :editable="false"
                        @on-change="selectTime"
                        v-model="dateTimes"
                        format="yyyy-MM-dd HH:mm:ss"
                        placement="bottom"
                        type="datetimerange"
                        :options='dateRangeDisabledOptions'
                        @on-clear='clearDatePicker'
                        @on-clickoutside='clickoutside'>
            </DatePicker>
          </Poptip>
          </Col>
        </Row>
      </div>
    </div>
    <Table :loading="loading"
           :height="this.tableHeight"
           ref="selection"
           :columns="columns"
           :data="orderList.orderListData"
           stripe
           class="table-list">
      <!-- 订单状态 -->
      <template slot-scope="{ row }"
                slot="orderStatus">
        <span>{{ row.orderStatus==="0"?"待付款":row.orderStatus==="1"?"待发货":row.orderStatus==="2"?"待收货":row.orderStatus==="3"?"已完成":row.orderStatus==="4"?"已取消":"" }}</span>
      </template>
      <!-- 订单类型 -->
      <template slot-scope="{ row }"
                slot="orderType">
        <span>{{ row.orderType==="3"?"游戏币订单":row.orderType==="4"?"游戏券订单":row.orderType==="5"?"游戏卡订单":row.orderType==="6"?"休闲项目订单":row.orderType==="7"?"商品订单" :row.orderType==="8"?"礼品订单":row.orderType==="9"?"团购订单":row.orderType==="10"?"兑换券订单":row.orderType==="11"?"办卡押金订单":row.orderType==="12"?"手工或导入订单" :row.orderType==="13"?"其他订单":row.orderType==="14"?"银票卡订单":row.orderType==="15"?"商铺租赁订单":row.orderType==="16"?"废品收入订单":row.orderType==="17"?"租赁押金订单":row.orderType==="18"?"机台租赁":row.orderType==="19"?"会员补卡": row.orderType==="21"?"套餐订单": row.orderType==="22" ? "SVIP会员订单" : "" }}</span>
      </template>
      <!-- 物流状态 -->
      <template slot-scope="{ row }"
                slot="shippingStatus">
        <span>{{ row.shippingStatus==="0"?"未发货":row.shippingStatus==="1"?"部分发货":row.shippingStatus==="2"?"已发货":row.shippingStatus==="3"?"部分退货":row.shippingStatus==="4"?"已退货":"" }}</span>
      </template>
      <!-- 支付类型 -->
      <template slot-scope="{ row }"
                slot="payType">
        <span>{{ row.payType==="0"?"扫码枪":row.payType==="1"?"主动扫码":row.payType==="2"?"公众号":row.payType==="3"?"银联刷卡":row.payType==="4"?"小程序":row.payType==="5"?"现金":row.payType==="6"?"app":row.payType==="7"?"对公转账":"" }}</span>
      </template>
      <!-- 支付方式 -->
      <template slot-scope="{ row }"
                slot="payCode">
        <span>{{ row.payCode==="ALIPAY"?"支付宝支付":row.payCode==="WEIXIN"?"微信支付":row.payCode==="CASH"?"现金支付":row.payCode==="UNION"?"银联支付":row.payCode==="TRANSFER_TO_PUBLIC_ACCOUNT"?"对公转账":row.payCode==="INTEGRAL"?"积分":row.payCode==="TICKET"?"彩票":row.payCode==="CURRENCY"?"游戏币":"" }}</span>
      </template>
      <template slot-scope="{row, index }"
                slot="action">
        <i class="iconsys icontuikuan"
           v-if="((row.orderStatus ==='3' && row.payAmount>0) || (row.payPlatform==='0' && row.orderStatus==='1') || (row.payPlatform==='0' && row.orderStatus==='2')) && beforeOneYearOrder(row.createTime) && (row.parentOrderCode === null || row.parentOrderCode === '') && (row.orderType !== '9' && row.orderType !== '8' && row.orderType !== '14')"
           title="退款"
           @click='refund(row, index)'></i>
        <!-- <i class="iconsys icontuikuan" v-if="((row.orderStatus ==='3' && row.payAmount>0 && (row.payCode==='ALIPAY' || row.payCode==='WEIXIN' || row.unionType === '1')) || (row.payPlatform==='0' && row.orderStatus==='1') || (row.payPlatform==='0' && row.orderStatus==='2')) && beforeOneYearOrder(row.createTime) && (row.parentOrderCode)" title="退款" @click='refund(row, index)'></i> -->
        <!-- <i class="iconsys icontuikuan" v-if="row.orderStatus ==='3' && row.payAmount>0 && (row.payCode==='ALIPAY' || row.payCode==='WEIXIN') && beforeOneYearOrder(row.createTime) || (row.payPlatform==='0' && row.orderStatus==='1' && beforeOneYearOrder(row.createTime)) || (row.payPlatform==='0' && row.orderStatus==='2' && beforeOneYearOrder(row.createTime))" title="退款" @click='refund(row, index)'></i> -->
      </template>
    </Table>
    <div class="page-box"
         style="margin-top: 20px">
      <Page :total="orderList.orderListTotal"
            ref="pages"
            :current.sync="searchObj.pageIndex"
            :page-size="searchObj.pageSize"
            @on-change="handlePage"
            @on-page-size-change="handlePageSize"
            show-sizer
            show-total />
    </div>
    <Modal v-model="refundModel"
           title="退款"
           :mask-closable="false"
           :closable="false">
      <p>确认要对此订单进行退款操作？</p>
      <div slot="footer">
        <Button type="text"
                @click="asyncCancel">取消</Button>
        <Button type="primary"
                @click="asyncOK"
                :disabled="loadingModel"
                :loading="loadingModel">确认</Button>
      </div>
    </Modal>
  </div>
</template>
<script>
import { orderQuery, orderRefund } from '@/api/order/index'
import { getShopList } from '@/api/system/store'
import { formatDate } from '@/libs/tools'
import myMixin from '@/mixins/dateRangePicker'
import { setTimeout } from 'timers'
export default {
  name: 'order_list',
  mixins: [myMixin],
  data () {
    return {
      exampleShow: true,
      loading: true,
      loadingModel: false,
      refundModel: false,
      tableHeight: 0,
      // 订单类型
      orderTypeList: [
        { value: '-1', label: '全部' },
        { value: '3', label: '游戏币订单' },
        { value: '4', label: '游戏券订单' },
        { value: '5', label: '游戏卡订单' },
        { value: '6', label: '休闲项目订单' },
        { value: '7', label: '商品订单' },
        { value: '8', label: '礼品订单' },
        { value: '9', label: '团购订单' },
        { value: '10', label: '兑换券订单' },
        { value: '11', label: '卡押金订单' },
        { value: '19', label: '补卡订单' },
        { value: '21', label: '套餐订单' },
        { value: '22', label: 'SVIP会员订单' }
      ],
      // 订单状态
      orderStatus: [
        { value: -1, label: '全部' },
        { value: 0, label: '待付款' },
        { value: 1, label: '待发货' },
        { value: 2, label: '待收货' },
        { value: 3, label: '已完成' },
        { value: 4, label: '已取消' }
        // { value: 5, label: '异常' }
      ],
      // 支付方式
      payMethod: [
        { value: -1, label: '全部' },
        { value: 'ALIPAY', label: '支付宝支付' },
        { value: 'WEIXIN', label: '微信支付' },
        { value: 'CASH', label: '现金支付' },
        { value: 'UNION', label: '银联支付' },
        { value: 'TRANSFER_TO_PUBLIC_ACCOUNT', label: '对公转账' }
        // { value: 'INTEGRAL', label: '积分' },
        // { value: 'TICKET', label: '彩票' },
        // { value: 'CURRENCY', label: '游戏币' }
      ],
      // 支付类型
      payType: [
        { value: -1, label: '全部' },
        { value: 0, label: '扫码枪' },
        { value: 1, label: '主动扫码' },
        { value: 2, label: '公众号' },
        { value: 3, label: '银联刷卡' },
        { value: 4, label: '小程序' },
        { value: 5, label: '现金' },
        { value: 6, label: 'app' },
        { value: 7, label: '对公转账' }
      ],
      // 物流状态
      // logisticsStatus: [
      //   { value: -1, label: '全部' },
      //   { value: 0, label: '已发货' },
      //   { value: 1, label: '未发货' }
      // ],
      // 表格列名称
      columns: [
        { title: '订单编号', key: 'orderCode', minWidth: 170, fixed: 'left' },
        { title: '父订单编号', key: 'parentOrderCode', minWidth: 200 },
        { title: '门店名称', key: 'shopName', minWidth: 300 },
        { title: '顾客姓名', key: 'customerName', minWidth: 200 },
        { title: '订单状态', slot: 'orderStatus', minWidth: 150 },
        { title: '订单类型', slot: 'orderType', minWidth: 150 },
        // { title: '门店ID', key: 'shopId', minWidth: 300 },
        { title: '商品总数量', key: 'totalQuantity', minWidth: 120 },
        { title: '游戏币数量', key: 'saleQuantity', minWidth: 120 },
        { title: '彩票兑换数量', key: 'exchangeQty', minWidth: 120 },
        { title: '抵扣金额(元)', key: 'discount', minWidth: 120 },
        { title: '应付金额(元)', key: 'payAmount', minWidth: 120 },
        { title: '订单总金额(元)', key: 'totalAmount', minWidth: 120 },
        { title: '支付方式', slot: 'payCode', minWidth: 150 },
        { title: '物流状态', slot: 'shippingStatus', minWidth: 150 },
        // { title: '支付类型', slot: 'payType', minWidth: 150 },
        { title: '完成时间', key: 'finishTime', minWidth: 200 },
        { title: '创建时间', key: 'createTime', minWidth: 200 }
        // { title: '操作', slot: 'action', minWidth: 80, fixed: 'right' }
      ],
      dateTimes: [
        formatDate(
          new Date(new Date().getTime() - 86400000 * 7),
          'yyyy-MM-dd hh:mm:ss'
        ),
        formatDate(new Date(), 'yyyy-MM-dd hh:mm:ss')
      ],
      orderCode: '',
      customerName: '',
      searchTime: {
        timeBegin: formatDate(
          new Date(new Date().getTime() - 86400000 * 7),
          'yyyy-MM-dd hh:mm:ss'
        ),
        timeEnd: formatDate(new Date(), 'yyyy-MM-dd hh:mm:ss')
      },
      searchObj: {
        orderType: '-1',
        orderCode: '',
        transactionId: '',
        orderStatus: -1,
        shopId: [],
        customerName: '',
        payMethod: -1,
        payType: -1,
        creationTimeBegin: formatDate(
          new Date(new Date().getTime() - 86400000 * 7),
          'yyyy-MM-dd hh:mm:ss'
        ),
        creationTimeEnd: formatDate(new Date(), 'yyyy-MM-dd hh:mm:ss'),
        pageIndex: 1,
        pageSize: 10
      },
      orderList: {
        orderListData: [],
        orderListTotal: 0
      },
      shopList: [],
      refundCode: '',
      refundShopId: ''
    }
  },
  created () {
    this.getShopList()
    if (this.hasPermission(['moms:order:refund'])) {
      this.columns.push({
        title: '操作',
        slot: 'action',
        minWidth: 80,
        fixed: 'right'
      })
    }
  },
  methods: {
    // 判断订单是否是一年之前的订单
    beforeOneYearOrder (time) {
      let pre = new Date()
      pre.setFullYear(pre.getFullYear() - 1)
      if (pre.getTime() - new Date(time).getTime() > 0) {
        return false
      } else {
        return true
      }
    },
    maxTagPlaceholder (num) {
      return '...'
    },
    filterSpace () {
      this.searchObj.customerName = this.searchObj.customerName.replace(
        /\s+/g,
        ''
      )
    },
    // 获取当前时间
    getFullYear () { },
    // 查询门店名称
    getShopList () {
      this.tableHeight = 0
      getShopList({
        permissionCode: 'moms:order:ordinary', // 查看普通订单
        merchantId: this.$store.state.user.merchantId, // 商户id
        offset: 0,
        limit: 9999
      })
        .then(res => {
          if (res.data.status === 200) {
            if (res.data.totalCount > 0) {
              this.shopList = res.data.data
              // let shopId = res.data.data[0].shopId
              // this.searchObj.shopId.push(shopId)
              this.searchObj.pageIndex = 1
              this.getOrderPage()
            } else {
              this.orderList = {
                orderListData: [],
                orderListTotal: 0
              }
              this.loading = false
            }
          } else {
            this.$Message.error(`${res.data.error}`)
          }
        })
        .catch(error => {
          this.$Message.error(`${this.showError(error)}`)
        })
    },

    // 点击退款
    refund (row, index) {
      this.refundCode = row.orderCode
      this.refundShopId = row.shopId
      this.refundModel = true
    },

    // 确认退款操作
    asyncOK () {
      this.orderRefundOperate()
    },
    // 退款取消
    asyncCancel () {
      this.refundCode = ''
      this.refundShopId = ''
      this.refundModel = false
    },

    // 分页操作
    handlePage (val) {
      this.searchObj.pageIndex = val
      this.getOrderPage()
    },
    handlePageSize (val) {
      this.searchObj.pageSize = val
      this.searchObj.pageIndex = 1
      this.getOrderPage()
    },
    // 查询按钮
    doSearch (type = 1) {
      // if (this.searchObj.shopId.length > 0) {
      if (type === 2) {
        this.searchObj.creationTimeBegin = this.searchTime.timeBegin
        this.searchObj.creationTimeEnd = this.searchTime.timeEnd
        this.customerName = this.searchObj.customerName
        this.orderCode = this.searchObj.orderCode
      }
      this.searchObj.pageIndex = 1
      this.searchObj.pageSize = 10
      this.getOrderPage()
      // } else {
      //   this.orderList = {
      //     orderListData: [],
      //     orderListTotal: 0
      //   }
      //   this.$Message.error(`请选择门店！`)
      //   this.tableHeight = 0
      // }
    },

    // 更多筛选
    exampleOpen () {
      this.exampleShow = !this.exampleShow
    },

    // 订单分页查询
    getOrderPage () {
      this.tableHeight = 0
      // if (this.searchObj.shopId.length > 0) {
      this.loading = true
      orderQuery({
        transactionId: this.searchObj.transactionId, // 支付流水号
        orderType: this.searchObj.orderType === '-1' ? '' : this.searchObj.orderType,
        orderCode: this.orderCode,
        merchantId: this.$store.state.user.merchantId, // 商户id
        orderStatus:
          this.searchObj.orderStatus === -1 ? '' : this.searchObj.orderStatus, // 订单状态
        shopId:
          this.searchObj.shopId.length > 1
            ? this.searchObj.shopId.join(',')
            : this.searchObj.shopId.join(''), // 门店ID
        // shopId: "05B39D14-7D88-4E39-8918-58495203D68A,",
        // shopName: this.searchObj.shopName.join(','), // 门店名称
        // customerName: this.searchObj.customerName, // 顾客姓名
        customerName: this.customerName,
        payCode:
          this.searchObj.payMethod === -1 ? '' : this.searchObj.payMethod, // 支付方式
        // payType: this.searchObj.payType === -1 ? '' : this.searchObj.payType, // 支付类型
        // shippingStatus: this.searchObj.logisticsStatus === -1 ? '' : this.searchObj.logisticsStatus, // 物流状态
        createTimeBegin: this.searchObj.creationTimeBegin, // 创建时间开始
        createTimeEnd: this.searchObj.creationTimeEnd, // 创建时间结束
        offset: (this.searchObj.pageIndex - 1) * this.searchObj.pageSize, // 分页OFFSET
        limit: this.searchObj.pageSize // 分页大小
      })
        .then(res => {
          this.loading = false
          if (res.data.status === 200) {
            this.orderList = {
              orderListData: res.data.data,
              orderListTotal: res.data.totalCount
            }
            if (res.data.data && res.data.data.length >= 10) {
              this.tableHeight = 537
            }
          } else {
            this.orderList = {
              orderListData: [],
              orderListTotal: 0
            }
            this.loading = false
            this.$Message.error(`${res.data.error}`)
          }
        })
        .catch(error => {
          this.$Message.error(`${this.showError(error)}`)
          this.loading = false
        })
      // }
    },

    // 退款操作
    orderRefundOperate () {
      this.loadingModel = true
      orderRefund({ orderCode: this.refundCode, shopId: this.refundShopId })
        .then(res => {
          if (res.data.status === 200) {
            setTimeout(() => {
              this.refundModel = false
              this.$Message.success('退款成功!')
              this.loadingModel = false
              this.refundCode = ''
              this.refundShopId = ''
              this.getOrderPage()
            }, 3000)
          } else {
            this.loadingModel = false
            this.$Message.error({
              content: '退款失败！' + res.data.error,
              duration: 3
            })
          }
        })
        .catch(error => {
          this.loadingModel = false
          this.$Message.error({
            content: `${this.showError(error)}`,
            duration: 3
          })
        })
    },

    // 切换时间
    selectTime (e) {
      this.searchTime.timeBegin = e[0]
      this.searchTime.timeEnd = e[1]
      // this.searchObj.creationTimeBegin = e[0]
      // this.searchObj.creationTimeEnd = e[1]
      // this.getOrderPage()
    },

    // 重置
    resetBtn () {
      this.dateTimes = [
        formatDate(
          new Date(new Date().getTime() - 86400000 * 7),
          'yyyy-MM-dd hh:mm:ss'
        ),
        formatDate(new Date(), 'yyyy-MM-dd hh:mm:ss')
      ]
      this.searchTime.timeBegin = formatDate(
        new Date(new Date().getTime() - 86400000 * 7),
        'yyyy-MM-dd hh:mm:ss'
      )
      this.searchTime.timeEnd = formatDate(new Date(), 'yyyy-MM-dd hh:mm:ss')
      this.customerName = ''
      this.orderCode = ''
      this.orderType = -1
      this.searchObj = {
        transactionId: '',
        orderStatus: -1,
        shopId: [],
        customerName: '',
        payMethod: -1,
        payType: -1,
        creationTimeBegin: formatDate(
          new Date(new Date().getTime() - 86400000 * 7),
          'yyyy-MM-dd hh:mm:ss'
        ),
        creationTimeEnd: formatDate(new Date(), 'yyyy-MM-dd hh:mm:ss'),
        pageIndex: 1,
        pageSize: 10
      }
      this.loading = true
      this.$refs.creationTime.handleClear()
      // let shopId = this.shopList[0].shopId
      // this.searchObj.shopId.push(shopId)
      this.doSearch()
    },
    showError (error) {
      return error.response && error.response.data.error
        ? error.response.data.error
        : error.data && error.data.error ? error.data.error : ''
    }
  },
  computed: {},
  mounted () {
    this.selectDateRangeDisabled(this.$refs.creationTime, 7)
  }
}
</script>

<style lang='less'>
#order-list {
  .search-box {
    .search-item {
      .ivu-date-picker {
        width: 280px;
        .ivu-date-picker-editor {
          width: 280px;
        }
      }
    }
  }
  .ivu-table-tip {
    span {
      position: absolute;
      width: 100px;
      left: 50%;
      margin-left: -50px;
    }
  }

  .select-shop-item {
    height: 35px;
    width: 210px;
    .ivu-select-selection {
      height: 35px;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
    }
    .ivu-tag {
      max-width: 100px;
    }
  }
  .select-shop-item .ivu-select-dropdown {
    width: 300px;
  }
  .select-shop-item .ivu-select-item {
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }
  .select-shop-item .ivu-select-input {
    width: 40px !important;
  }
  .ivu-poptip-body {
    padding: 8px 16px;
    background: #585e6b;
    border-radius: 3px;
  }
  .ivu-poptip-body-content-inner {
    color: #fff;
  }
  .ivu-poptip-popper[x-placement^='top'] .ivu-poptip-arrow:after {
    border-top-color: #585e6b;
  }
}
</style>
